import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Typography,
  Divider,
  Switch,
  FormControlLabel,
  Autocomplete,
  InputAdornment,
  Alert,
  Skeleton,
} from '@mui/material';
import {
  Save as SaveIcon,
  Cancel as CancelIcon,
  Business as BusinessIcon,
  AccountTree as TreeIcon,
} from '@mui/icons-material';
import { useNavigate, useParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

import {
  UpdateOrganizationRequest,
  Organization,
  Status,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { organizationService } from '@/services/organizationService';
import { PageHeader } from '@/components/common/PageHeader';

// 表单验证模式
const organizationFormSchema = z.object({
  name: z.string().min(1, '组织名称不能为空').max(100, '组织名称不能超过100个字符'),
  code: z.string()
    .min(1, '组织编码不能为空')
    .max(50, '组织编码不能超过50个字符')
    .regex(/^[a-zA-Z0-9_-]+$/, '组织编码只能包含字母、数字、下划线和横线'),
  description: z.string().optional(),
  parentId: z.string().optional(),
  status: z.enum(['active', 'inactive', 'pending', 'suspended']),
  sort: z.number().min(0, '排序值不能为负数').max(9999, '排序值不能超过9999'),
  settings: z.object({
    maxUsers: z.number().min(1, '用户数限制不能少于1').max(10000, '用户数限制不能超过10000'),
    maxSubOrganizations: z.number().min(0, '子组织数限制不能为负数').max(1000, '子组织数限制不能超过1000'),
    allowSubOrgCreation: z.boolean(),
    inheritParentSettings: z.boolean(),
    features: z.array(z.string()).optional(),
  }),
  managerUserId: z.string().optional(),
});

type OrganizationFormData = z.infer<typeof organizationFormSchema>;

const OrganizationEditPage: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const queryClient = useQueryClient();
  const { hasPermission, currentTenant } = useAuth();
  const { showToast } = useAppNotifications();

  const [isSubmitting, setIsSubmitting] = useState(false);

  // 表单控制
  const {
    control,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm<OrganizationFormData>({
    resolver: zodResolver(organizationFormSchema),
  });

  // 获取组织详情
  const {
    data: organizationData,
    isLoading: organizationLoading,
    error: organizationError,
  } = useQuery({
    queryKey: ['organization', id],
    queryFn: () => organizationService.getOrganization(id!),
    enabled: !!id,
  });

  // 获取组织列表（用于选择父组织）
  const { data: organizationsData } = useQuery({
    queryKey: ['organizations', { tenantId: currentTenant?.id }],
    queryFn: () => organizationService.getOrganizations({ tenantId: currentTenant?.id }),
    enabled: !!currentTenant,
  });

  // 获取用户列表（用于选择管理员）
  const { data: usersData } = useQuery({
    queryKey: ['users', { organizationId: currentTenant?.id }],
    queryFn: () => fetch(`/api/users?organizationId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 当组织数据加载完成时，设置表单默认值
  useEffect(() => {
    if (organizationData?.data) {
      const org = organizationData.data;
      reset({
        name: org.name,
        code: org.code,
        description: org.description || '',
        parentId: org.parentId || '',
        status: org.status,
        sort: org.sort,
        settings: {
          maxUsers: org.settings?.maxUsers || 100,
          maxSubOrganizations: org.settings?.maxSubOrganizations || 10,
          allowSubOrgCreation: org.settings?.allowSubOrgCreation ?? true,
          inheritParentSettings: org.settings?.inheritParentSettings ?? true,
          features: org.settings?.features || [],
        },
        managerUserId: org.managerUserId || '',
      });
    }
  }, [organizationData, reset]);

  // 更新组织
  const updateMutation = useMutation({
    mutationFn: (data: UpdateOrganizationRequest) => organizationService.updateOrganization(id!, data),
    onSuccess: (response) => {
      showToast({
        type: 'success',
        title: '更新成功',
        message: '组织信息已成功更新',
      });
      queryClient.invalidateQueries(['organizations']);
      queryClient.invalidateQueries(['organization', id]);
      navigate('/organizations');
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '更新失败',
        message: error.message || '更新组织时发生错误',
      });
    },
  });

  // 提交表单
  const onSubmit = async (data: OrganizationFormData) => {
    if (!hasPermission('organization.edit')) {
      showToast({
        type: 'error',
        title: '权限不足',
        message: '您没有编辑组织的权限',
      });
      return;
    }

    setIsSubmitting(true);
    try {
      await updateMutation.mutateAsync(data as UpdateOrganizationRequest);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 构建组织树形选项（排除当前组织及其子组织）
  const buildOrganizationOptions = (orgs: Organization[], level = 0, excludeIds: string[] = []): Array<{ label: string; value: string; level: number }> => {
    const options: Array<{ label: string; value: string; level: number }> = [];
    
    orgs.forEach(org => {
      if (excludeIds.includes(org.id)) return;
      
      const prefix = '　'.repeat(level);
      options.push({
        label: `${prefix}${org.name}`,
        value: org.id,
        level,
      });
      
      const children = orgs.filter(child => child.parentId === org.id && !excludeIds.includes(child.id));
      if (children.length > 0) {
        options.push(...buildOrganizationOptions(children, level + 1, excludeIds));
      }
    });
    
    return options;
  };

  // 获取需要排除的组织ID（当前组织及其所有子组织）
  const getExcludeIds = (currentOrgId: string, allOrgs: Organization[]): string[] => {
    const excludeIds = [currentOrgId];
    
    const findChildren = (parentId: string) => {
      const children = allOrgs.filter(org => org.parentId === parentId);
      children.forEach(child => {
        excludeIds.push(child.id);
        findChildren(child.id);
      });
    };
    
    findChildren(currentOrgId);
    return excludeIds;
  };

  const organizationOptions = organizationsData?.data && id
    ? buildOrganizationOptions(
        organizationsData.data.filter(org => !org.parentId),
        0,
        getExcludeIds(id, organizationsData.data)
      )
    : [];

  // 可用功能选项
  const availableFeatures = [
    { id: 'advanced_permissions', label: '高级权限管理' },
    { id: 'custom_workflows', label: '自定义工作流' },
    { id: 'data_analytics', label: '数据分析' },
    { id: 'api_access', label: 'API访问' },
    { id: 'custom_branding', label: '自定义品牌' },
    { id: 'audit_logs', label: '审计日志' },
  ];

  if (!id) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">组织ID参数缺失</Alert>
      </Box>
    );
  }

  if (!currentTenant) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="warning">请先选择租户</Alert>
      </Box>
    );
  }

  if (organizationError) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">
          加载组织信息失败：{(organizationError as any).message}
        </Alert>
      </Box>
    );
  }

  if (organizationLoading) {
    return (
      <Box sx={{ p: 3 }}>
        <PageHeader
          title="编辑组织"
          description="编辑组织信息"
          breadcrumbs={[
            { label: '首页', path: '/' },
            { label: '组织管理', path: '/organizations' },
            { label: '编辑组织' },
          ]}
        />
        <Card>
          <CardContent>
            <Grid container spacing={3}>
              {Array.from({ length: 12 }).map((_, index) => (
                <Grid item xs={12} md={6} key={index}>
                  <Skeleton height={56} />
                </Grid>
              ))}
            </Grid>
          </CardContent>
        </Card>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="编辑组织"
        description={`编辑组织：${organizationData?.data?.name}`}
        breadcrumbs={[
          { label: '首页', path: '/' },
          { label: '组织管理', path: '/organizations' },
          { label: '编辑组织' },
        ]}
      />

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Grid container spacing={3}>
              {/* 基本信息 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  基本信息
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="name"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织名称"
                      fullWidth
                      required
                      error={!!errors.name}
                      helperText={errors.name?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <BusinessIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="code"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织编码"
                      fullWidth
                      required
                      disabled // 编辑时不允许修改编码
                      error={!!errors.code}
                      helperText={errors.code?.message || '组织编码创建后不可修改'}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织描述"
                      fullWidth
                      multiline
                      rows={3}
                      placeholder="请输入组织的详细描述..."
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="parentId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>上级组织</InputLabel>
                      <Select
                        {...field}
                        label="上级组织"
                        startAdornment={
                          <InputAdornment position="start">
                            <TreeIcon />
                          </InputAdornment>
                        }
                      >
                        <MenuItem value="">无（作为顶级组织）</MenuItem>
                        {organizationOptions.map((option) => (
                          <MenuItem key={option.value} value={option.value}>
                            {option.label}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="status"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>状态</InputLabel>
                      <Select {...field} label="状态">
                        <MenuItem value="active">启用</MenuItem>
                        <MenuItem value="inactive">禁用</MenuItem>
                        <MenuItem value="pending">待审核</MenuItem>
                        <MenuItem value="suspended">暂停</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="sort"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="排序值"
                      type="number"
                      fullWidth
                      error={!!errors.sort}
                      helperText={errors.sort?.message || '数值越小排序越靠前'}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="managerUserId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>组织管理员</InputLabel>
                      <Select {...field} label="组织管理员">
                        <MenuItem value="">暂不设置</MenuItem>
                        {usersData?.data?.map((user: any) => (
                          <MenuItem key={user.id} value={user.id}>
                            {user.profile.fullName} ({user.username})
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              {/* 配置设置 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  配置设置
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="settings.maxUsers"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="用户数限制"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.maxUsers}
                      helperText={errors.settings?.maxUsers?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="settings.maxSubOrganizations"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="子组织数限制"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.maxSubOrganizations}
                      helperText={errors.settings?.maxSubOrganizations?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Box sx={{ pt: 2 }}>
                  <Controller
                    name="settings.allowSubOrgCreation"
                    control={control}
                    render={({ field }) => (
                      <FormControlLabel
                        control={<Switch {...field} checked={field.value} />}
                        label="允许创建子组织"
                      />
                    )}
                  />
                </Box>
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="settings.inheritParentSettings"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="继承父组织设置"
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12}>
                <Controller
                  name="settings.features"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={availableFeatures}
                      getOptionLabel={(option) => option.label}
                      value={availableFeatures.filter(feature => 
                        field.value?.includes(feature.id)
                      )}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map(item => item.id));
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="可用功能"
                          placeholder="选择组织可使用的功能..."
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              {/* 操作按钮 */}
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 3 }}>
                  <Button
                    variant="outlined"
                    startIcon={<CancelIcon />}
                    onClick={() => navigate('/organizations')}
                    disabled={isSubmitting}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    startIcon={<SaveIcon />}
                    disabled={isSubmitting || !hasPermission('organization.edit')}
                  >
                    {isSubmitting ? '更新中...' : '更新组织'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default OrganizationEditPage;